import hashlib
import string
import random
import datetime
import rsa
import sys
import os
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.BlockChain as BlockChain

def hashFunction(data):  #data格式是元组
    try:
        data_str = str(data) if not isinstance(data,str) else data
        hash1 = hashlib.sha256(data_str.encode("utf-8"))
        hex_digest1 = hash1.hexdigest()
        return hex_digest1
    except Exception as e:
        print(f'DID部分创建hash错误，错误为{e}')
        return 0


def store_user_data_to_db(user_data):  #user_data格式要注意是字典
    import backend.DID.DataBase as DataBase
    db_path = 'user.db'
    table_name_user = "user"
    try:
        if DataBase.insert_data(db_path,table_name_user,user_data):
            return 1
        else:
            return 0

        if DataBase.insert_data(db_path,table_name_user,user_data):
            return 1
        else:
            return 0

    except Exception as e:
        print(f"DID部分创建身份时上传用户信息进入数据库错误，错误为{e}")
        return 0


def store_user_data_to_bc(user_data):
    table_name_blockchain = "blockchain"
    try:
        if BlockChain.insert_into_blockchain(table_name_blockchain,user_data):
            return 1
        else:
            return 0

        if BlockChain.insert_into_blockchain(table_name_blockchain,user_data):
            return 1
        else:
            return 0

    except Exception as e:
        print(f"DID部分上传DID文档信息进入区块链出错，错误为{e}")
        return 0


def CreateIdentity1(device_id,cpu_id,Disc_id,user_name,password):
    from backend.DID.En_Decrypt_Management import encrypt_privatekey

    try:
        device_information = (
            device_id,
            cpu_id,
            Disc_id
        )
        hex_digest1 = hashFunction(device_information)  #这个就是hash1
        if not hex_digest1:
            return 0

        did_method = "p2p_did_chat"
        all_characters = string.ascii_letters + string.digits
        random_number = ''.join(random.choice(all_characters) for _ in range(10))   #生成DID
        did = f"did:{did_method}:{random_number}"

        whole_data = (
            device_information,
            user_name,
            password
        ) #顺序不要改变

        hex_digest2 = hashFunction(whole_data)
        if not hex_digest2:
            return 0

        try:
            public_key, private_key = rsa.newkeys(1024)
            public_key_pem = public_key.save_pkcs1().decode("UTF-8")
            private_key_pem = private_key.save_pkcs1().decode("UTF-8")
        except Exception as e:
            print(f"DID部分 密钥生成出错，错误为{e}")
            return 0
        #存储钥匙要加密存储
        try:
            encrypt_private_key = encrypt_privatekey(private_key_pem, password)
        except Exception as e:
            print(f"DID部分私钥加密出错，错误为{e}")
            return 0

        created_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  #创建时间
        updated_time = created_time  #创建时间就是更新的时间

        authentication = 'RsaVerificationKey2018'
        blockchain_data = {
            'hash1':hex_digest1,
            'id':did,
            'hash2':hex_digest2,
            'publickey':public_key_pem,
            'updated':updated_time,
            'created':created_time,
            'authentication':authentication
        }
        #存储进入区块链
        sqlite_user_data = {
            'hash1':hex_digest1,
            'id':did,
            'hash2':hex_digest2,
            'username':user_name,
            'password':password,
            'private_key':encrypt_private_key
        }
        #存储进入数据库
        try:
            if store_user_data_to_db(sqlite_user_data) and store_user_data_to_bc(blockchain_data) :
                return did
            else:
                return 0
        except Exception as e:
            print(f"区块链插入失败")
            return 0

    except Exception as e:
        print(f"DID部分身份创建出错，错误为{e}")
        return 0


